package com.scommunity.utils;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.scommunity.domain.AliPayBean;
import com.scommunity.domain.Pay;
import com.scommunity.mapper.PayMapper;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Data
@Configuration
public class Alipay {
    @Autowired
    PayMapper payMapper;

    /**日志对象*/
    private static final Logger logger = LoggerFactory.getLogger(Alipay.class);

    private final String format = "json";

    /**
     * appId
     */
    @Value("${app.appId}")
    private String appId;

    /**
     * 商户私钥 这个是应用私钥，也是生成器生成的
     */
    @Value("${app.privateKey}")
    private String privateKey;

    /**
     * 支付宝公钥
     */
    @Value("${app.publicKey}")
    private String publicKey;

    /**
     * 服务器异步通知页面路径，需要公网能访问到
     */
    @Value("${app.notifyUrl}")
    private String notifyUrl;

    /**
     * 服务器同步通知页面路径，需要公网能访问到
     */
    @Value("${app.returnUrl}")
    private String returnUrl;

    /**
     * 签名方式
     */
    @Value("${app.signType}")
    private String signType;

    /**
     * 字符编码格式
     */
    @Value("${app.charset}")
    private String charset;

    /**
     * 支付宝网关
     */
    @Value("${app.gatewayUrl}")
    private String gatewayUrl;

    public String pay(AliPayBean aliPayBean) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(
                gatewayUrl, appId, privateKey, format, charset, publicKey, signType);

        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setNotifyUrl(notifyUrl);
        //alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setBizContent(JSON.toJSONString(aliPayBean));
        logger.info("封装请求支付宝付款参数为:{}", JSON.toJSONString(alipayRequest));

        String result = alipayClient.pageExecute(alipayRequest).getBody();
        logger.info("请求支付宝付款返回参数为:{}", result);

        return result;
    }
    /**
     * 支付宝异步请求逻辑
     */

    public String notify(Map<String, String> conversionParams) {
        // 签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
        boolean signVerified = false;
       // System.out.println(conversionParams);

        try {
            // 调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(conversionParams, publicKey,
                    charset, signType);

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        if (signVerified) {
           // System.out.println(111111);
            // 验签通过
            String outTradeNo = conversionParams.get("out_trade_no");// 获取商户之前传给支付宝的订单号（商户系统的唯一订单号）
        /*    // 获取需要保存的数据
            String appId2 = conversionParams.get("app_id");// 支付宝分配给开发者的应用Id
            String notifyTime = conversionParams.get("notify_time");// 通知时间:yyyy-MM-dd HH:mm:ss
            String gmtCreate = conversionParams.get("gmt_create");// 交易创建时间:yyyy-MM-dd HH:mm:ss
            String gmtPayment = conversionParams.get("gmt_payment");// 交易付款时间
            String gmtRefund = conversionParams.get("gmt_refund");// 交易退款时间
            String gmtClose = conversionParams.get("gmt_close");// 交易结束时间
            String tradeNo = conversionParams.get("trade_no");// 支付宝的交易号
            String outBizNo = conversionParams.get("out_biz_no");// 商户业务号(商户业务ID，主要是退款通知中返回退款申请的流水号)
            String buyerLogonId = conversionParams.get("buyer_logon_id");// 买家支付宝账号
            String sellerId = conversionParams.get("seller_id");// 卖家支付宝用户号
            String sellerEmail = conversionParams.get("seller_email");// 卖家支付宝账号
            Double totalAmount = Double.parseDouble(conversionParams.get("total_amount"));// 订单金额:本次交易支付的订单金额，单位为人民币（元）
            String receiptAmount = conversionParams.get("receipt_amount");// 实收金额:商家在交易中实际收到的款项，单位为元
            String invoiceAmount = conversionParams.get("invoice_amount");// 开票金额:用户在交易中支付的可开发票的金额
            String buyerPayAmount = conversionParams.get("buyer_pay_amount");// 付款金额:用户在交易中支付的金额
            String tradeStatus = conversionParams.get("trade_status");// 获取交易状态*/

            // 支付宝官方建议校验的值（out_trade_no、total_amount、sellerId、app_id）
            String tradeStatus = conversionParams.get("trade_status");
            if (tradeStatus.equals("TRADE_SUCCESS")){
            Pay pay = payMapper.selectOne(new QueryWrapper<Pay>().eq("pay_num", outTradeNo));
            pay.setPayStatus("2");
            pay.setPayWay("2");
            int payStatusCode = payMapper.update(pay, new UpdateWrapper<Pay>().eq("pay_num", pay.getPayNum()));
            return "success";
            }
            return "fail";
        } else { // 验签不通过
            return "fail";
        }

    }


}


